import java.util.*;
/**
 * 要求：
 * 1. 实现 filter 方法，构造函数实现可以修改（示例提供默认实现）
 * 2. 实时过滤，性能最优
 */

public class FilterKeywords {
    private Set<String> keywordsSet = new HashSet<>();// 关键词集合

    public FilterKeywords(Set<String> keywordsSet) {
        this.keywordsSet = keywordsSet;
    }

    public static void main(String[] args) {
        Set<String> keywordsSet = new HashSet<>();
        keywordsSet.add("百度");
        keywordsSet.add("谷歌");
        keywordsSet.add("阿里");
        keywordsSet.add("欢聚时代");
        keywordsSet.add("习悦");
        FilterKeywords filterKeywords = new FilterKeywords(keywordsSet);
        String txt = "习悦百度，我想用百度一下，然后百度不行，所以我就用谷歌，谷歌挺方便，谷歌可以找很多东西" +
                "阿里巴巴很好，阿里云也不错。还有阿里妈妈，淘宝天猫也是阿里的。我在做欢聚时代的笔试,现在我在习悦上班";
        Map<String, Integer> map = filterKeywords.filter(txt);
        for (Map.Entry<String, Integer> mm : map.entrySet())
            System.out.println("Key: " + mm.getKey() + ",Value: " + mm.getValue());
    }

    /**
     * 过滤方法
     *
     * @param txt 待过滤的评论内容
     * @return 过滤出来的关键词及对应出现的次数
     */
    public Map<String, Integer> filter(String txt) {
        Map<String, Integer> value = new HashMap<>();
        Iterator iterator = keywordsSet.iterator();
        String flag;
        while (iterator.hasNext()) {
            flag = iterator.next().toString();
            int result = getIndexOf(txt, flag);
            if (result > 0) {
                value.put(flag, result);
            }
        }
        return value;
    }

    /**
     * sundy算法匹配
     * @param txt
     * @param flag
     * @return
     */
    private int getIndexOf(String txt, String flag) {
        char[] dest = txt.toCharArray();
        char[] patt = flag.toCharArray();
        int i = 0, j = 0;
        int sum = 0;
        while (i <= (dest.length - patt.length + j)) {
            if (dest[i] != patt[j]) {
                if (i == (dest.length - patt.length + j)) {
                    break;
                }
                int pos = contains(patt, dest[i + patt.length - j]);
                if (pos == -1) {
                    i = i + patt.length + 1 - j;
                    j = 0;
                } else {
                    i = i + patt.length - pos - j;
                    j = 0;
                }
            } else {
                if (j == (patt.length - 1)) {  //找到匹配
                    sum++;
                    i = i - j + 1;
                    j = 0;
                } else {
                    i++;
                    j++;
                }
            }
        }
        return sum;
    }

    private int contains(char[] chars, char target) {
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == target) {
                return i;
            }
        }
        return -1;
    }
}